#include "remoteserver.h"
#include "capture/screencapture.h"

RemoteServer::RemoteServer(QObject *parent) : QTcpServer(parent)
{
}

void RemoteServer::pushWindow(ScreenCapture *window)
{
    windowList.push_back(window);
}

void RemoteServer::removeWindow(ScreenCapture *window)
{
    windowList.removeAll(window);
}

void RemoteServer::incomingConnection(qintptr socketDescriptor)
{
    RemoteHost *host = new RemoteHost(this);
    if(!host->setSocketDescriptor(socketDescriptor))
    {
        host->abort();
        delete host;
        return;
    }
    connect(host, &RemoteHost::disconnected, this, &RemoteServer::on_host_disconnected);
    connect(host, &RemoteHost::receivedVersion, this, &RemoteServer::on_receivedVersion);
    connect(host, &RemoteHost::receivedKey, this, &RemoteServer::receivedKey);
    connect(host, &RemoteHost::receivedMouse, this, &RemoteServer::receivedMouse);
    connect(host, &RemoteHost::receivedWheel, this, &RemoteServer::receivedWheel);
    connect(host, &RemoteHost::receivedCutText, this, &RemoteServer::receivedCutText);
    connect(host, &RemoteHost::receivedStartCap, this, &RemoteServer::startCap);
    connect(host, &RemoteHost::receivedPauseCap, this, &RemoteServer::pauseCap);
    VerifiList.push_back(host);
    host->sendVersion();
}

void RemoteServer::on_host_disconnected()
{
    RemoteHost *host = dynamic_cast<RemoteHost*>(sender());
    if(host == nullptr)
    {
        return;
    }
    hostList.removeAll(host);
    VerifiList.removeAll(host);
    if(hostList.isEmpty())
    {
        emit stopCap();
    }
}

void RemoteServer::on_receivedVersion(const QByteArray &version)
{
    RemoteHost* host = dynamic_cast<RemoteHost*>(sender());
    if(!host)
    {
        return;
    }
    QByteArray curVersion = RemoteHost::getVersion();
    if(curVersion != version)
    {
        qDebug()<<"版本验证失败："<<version;
        host->abort();
        return;
    }
    qDebug()<<"版本验证成功";
    foreach(ScreenCapture* wid, windowList)
    {
        qDebug()<<QString("发送窗口:%1 宽:%2 高:%3 编码:%4").arg(wid->winId()).arg(wid->width()).arg(wid->height()).arg(wid->pixelFormat());
        host->sendCreateWindow(wid->winId(), wid->width(), wid->height(), wid->pixelFormat());
    }
    VerifiList.removeAll(host);
    hostList.push_back(host);
    emit startCap();
}

bool RemoteServer::sendWindowFramebuffer(int wid, const QByteArray &data)
{
    foreach(RemoteHost* host, hostList)
    {
        host->sendWindowFramebuffer(wid, data);
    }
    return true;
}

bool RemoteServer::sendCutText(const QString &text)
{
    foreach(RemoteHost* host, hostList)
    {
        host->sendCutText(text);
    }
    return true;
}

bool RemoteServer::sendCreateWindow(int wid, int width, int height, int codec)
{
    foreach(RemoteHost* host, hostList)
    {
        qDebug()<<QString("发送窗口:%1 宽:%2 高:%3 编码:%4").arg(wid).arg(width).arg(height).arg(codec);
        host->sendCreateWindow(wid, width, height, codec);
    }
    return true;
}
